package com.example.demo.controller;

import cn.hutool.core.util.ObjectUtil;
import com.example.demo.common.enums.CodeEnum;
import com.example.demo.common.exception.BaseRuntimeException;
import com.example.demo.common.result.R;
import com.example.demo.common.utils.JwtUtil;
import com.example.demo.entity.UserT;
import com.example.demo.service.UserTService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
public class AuthController {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserTService userTService;

    /**
     * 获取token
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/login")
    public R<?> login(@RequestParam String username, @RequestParam String password) {
        UserT userT = userTService.selectByUserName(username);
        if (ObjectUtil.isEmpty(userT)) {
            throw new BaseRuntimeException(CodeEnum.FAILURE.getCode(), "用户不存在");
        }
        // 这里应该进行用户名和密码的验证
        if (userT.getUserName().equals(username) && userT.getPassword().equals(password)) {
            String token = jwtUtil.generateToken(username);
            return R.success().data(token);
        } else {
            return R.fail().data("用户密码错误");
        }
    }

    /**
     * 验证Token
     * @param token
     * @return
     */
    @GetMapping("/profile")
    public ResponseEntity<?> profile(@RequestHeader("Authorization") String token) {
        if (jwtUtil.validateToken(token.replace("Bearer ", ""))) {
            String username = jwtUtil.getUsernameFromToken(token.replace("Bearer ", ""));
            return ResponseEntity.ok().body("Profile for " + username);
        } else {
            return ResponseEntity.status(401).body("Invalid token");
        }
    }
}
